package com.springclouddemo.eurekaclientconsumerhystrix.controllers;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 何昌杰
 */
@RestController
public class DemoController {
    private static final Logger log= LoggerFactory.getLogger(DemoController.class);
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/helloribbon")
    public void ribbonDemo(){
        ServiceInstance choose = this.loadBalancerClient.choose("eureka-client-provider");
        log.info(choose.getInstanceId()+","+choose.getHost()+":"+choose.getPort());
    }

    @GetMapping("/hello/{name}")
    @HystrixCommand(fallbackMethod = "demo2Fallback",
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE")
        }
    )
    public String demo1(@PathVariable("name") String name){
        return this.restTemplate.getForObject("http://localhost:7100/hello/"+name,String.class);
    }

    public String demo2Fallback(String name){
        return "模拟默认请求响应";
    }
}
